<!-- Bot Read Me -->
<!-- Author: Edwin -->
<template>
  <el-dialog :close-on-press-escape="false"
             :close-on-click-modal="false"
             :visible.sync="visible"
             :append-to-body="true"
             width="545px"
             top="100px"
             class="cui-custom-css-bot-edit"
             @close="canceldialog">
    <div slot="title"
         class="header-title">
      <span class="title-name">{{isClone ? 'Clone' : !dataForm.id ? $t('custom.bots.edit.titleAdd') : $t('custom.bots.edit.titleEdit')}}</span>
      <view-linked-info :linkKey="'createNewBotwiki'"></view-linked-info>
    </div>
    <div class="area">
      <div class="action add_update_bot">
        <el-form ref="dataForm"
                 v-loading="loading"
                 :model="dataForm"
                 size='mini'
                 label-position='top'
                 class="form-data"
                 :rules="dataFormRules">
          <el-form-item :label="$t('custom.botStore.name')"
                        prop="name">
            <el-input v-model="dataForm.name"
                      maxlength="70"
                      :placeholder="$t('custom.botStore.enterName')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('custom.bots.integrationName')"
                        v-show="false"
                        prop="integration">
            <el-select v-model="dataForm.integration"
                       style="width: 100%;"
                       clearable
                       filterable
                       collapse-tags
                       default-first-option
                       :disabled="isStartFromTemplate"
                       :placeholder="$t('custom.bots.enterIntegrationName')">
              <el-option v-for="(item,i) in integrationList"
                         :key="i"
                         :label="item.name"
                         :value="item.subjectCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="roleIdList"
                        :label="$t('custom.reports.role')">
            <el-select v-model="dataForm.roleIdList"
                       filterable
                       clearable
                       multiple
                       default-first-option
                       :placeholder="$t('custom.reports.role')"
                       style="width: 100%;">
              <el-option v-for="(its,iii) in fullRoleList"
                         :key="iii"
                         :label="its.name"
                         :value="its.roleId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="tagList"
                        :label="$t('custom.reports.tag')">
            <el-select v-model="dataForm.tagList"
                       filterable
                       clearable
                       multiple
                       allow-create
                       collapse-tags
                       default-first-option
                       :placeholder="$t('custom.reports.tag')"
                       style="width: 100%;">
              <el-option v-for="(its,iii) in tags"
                         :key="iii"
                         :label="its.name"
                         :value="its.name">
                         <div style="display: flex;justify-content:space-between;">
                            <ZTooltip :content="its.name"
                               :line="1"
                              placement="top">
                                <span style="flex:1">{{ its.name }}</span>
                            </ZTooltip>
                            <span>
                              <el-button 
                                           style="float: right;font-size: 14px;margin-top: 3px;margin-left: 10px;"
                                           size='mini'
                                           type="text"
                                           @click.stop="deleteTag(its)">
                                  <i class="cuifont icon_delete"
                                     style="font-size:14px;color:#CCC"></i>
                                </el-button>
                            </span>
                         </div>
                        </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('custom.botStore.description')"
                        prop="description">
            <el-input v-model="dataForm.description"
                      :rows="8"
                      resize='none'
                      maxlength="500"
                      :placeholder="$t('custom.botStore.enterDescription')"
                      type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <div class="addBotFooter ">
          <el-button type="text"
                     v-if="!isClone && $hasPermission('sys:bots:moreedit')"
                     @click="botsMoreEdit"
                     size="small">{{ $t('custom.reports.moreedit') }}
          </el-button>
          <el-button size="small"
                     style="margin-left:20px;"
                     v-if="reselectBtn"
                     @click="reselectTem">{{ $t('custom.bots.edit.reselect') }}
          </el-button>
          <el-button size="small"
                     type="primary"
                     :loading="submitBtnLoading"
                     v-if="dataForm.id ? $hasPermission('sys:bots:edit') : $hasPermission('sys:bots:add')"
                     @click="dataFormSubmitHandle()">{{ dataForm.id ? $t('custom.botStore.save') : $t('confirm') }}
          </el-button>
        </div>
        <el-dialog :visible.sync="moreEditVisible"
                   :title="$t('custom.reports.moreedit')"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   :modal='false'
                   style="margin-top:-16px"
                   width="545px">
          <div class="screen-y scroll-css"
               style="height:300px;">
            <el-form :model="dataForm"
                     style="padding:0 20px"
                     ref="moreEditDataForm"
                     :rules="FormRules"
                     label-position="top">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item prop="businessType"
                                :label="$t('custom.dataset.businessType')">
                    <el-select v-model="dataForm.businessType"
                               :placeholder="$t('custom.dataset.businessType')"
                               style="width: 100%;"
                               :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                      <el-option v-for="its in businessTypeList"
                                 :key="its.dictValue"
                                 :label="its.dictLabel"
                                 :value="its.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <!-- <span>{{dataForm}}</span> -->
                  <el-form-item prop="tenantCode"
                                placeholder="Client"
                                :label="$t('custom.dataset.tenantCode')">
                    <select-client-id v-model="dataForm.tenantCode"
                                      :disabled="dataForm.businessType==='Template' || dataForm.businessType==='MSPbots Internal'"
                                      :width="100"></select-client-id>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="status"
                                :label="$t('custom.dataset.status')">
                    <el-select v-model="dataForm.status"
                               :placeholder="$t('custom.dataset.status')"
                               style="width: 100%;">
                      <el-option v-for="its in statusList"
                                 :key="its.dictValue"
                                 :label="its.dictLabel"
                                 :value="its.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <!-- <el-form-item prop="teamId"
                            :label="$t('custom.dataset.team')" >
                  <select-team-id v-model="dataForm.teamId"  :width="100"></select-team-id>
              </el-form-item> -->
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="da"
                                :label="$t('custom.report.da')">
                    <el-select v-model="dataForm.da"
                               clearable
                               filterable
                               :placeholder="$t('custom.report.da')"
                               style="width: 100%;">
                      <el-option v-for="(its, index3) in userList"
                                 :key="index3"
                                 :label="its.realname"
                                 :value="its.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="po"
                                :label="$t('custom.report.po')">
                    <el-select v-model="dataForm.po"
                               clearable
                               filterable
                               :placeholder="$t('custom.report.po')"
                               style="width: 100%;">
                      <el-option v-for="(its, index3) in userList"
                                 :key="index3"
                                 :label="its.realname"
                                 :value="its.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="jiraNumber"
                                :label="$t('custom.reports.jiraNumber')">
                    <el-input v-model="dataForm.jiraNumber"
                              @keyup.enter.native.stop
                              type="text"
                              style="width: 100%"
                              rows="3"
                              :placeholder="$t('custom.reports.jiraNumber')">
                      <JiraNumberLink slot="suffix"
                                      :jiraNumber="dataForm.jiraNumber" />
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="classification"
                                :label="$t('custom.bots.edit.classification')">
                    <el-select v-model="dataForm.classification"
                               :placeholder="$t('custom.bots.edit.classification')"
                               style="width: 100%;">
                      <el-option v-for="its in classificationList"
                                 :key="its.dictValue"
                                 :label="its.dictLabel"
                                 :value="its.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12"
                        style="display: flex;justify-content: space-between;align-items: center;">
                  <el-form-item prop="shared"
                                :label="$t('custom.dataset.shared')">
                    <el-switch v-model="dataForm.shared"
                               active-color="#007bff"
                               inactive-color="#dcdfe6">
                    </el-switch>
                  </el-form-item>
                  <el-form-item prop="defaultInstall " v-if="$hasPermission('sys:bot:defaultinstall')"
                                :label="$t('custom.dataset.defaultInstall')">
                    <el-switch
                      v-model="dataForm.applyTenant"
                      active-color="#007bff"
                      inactive-color="#dcdfe6">
                    </el-switch>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
          </div>
          <template slot="footer">
            <el-button @click="moreEditVisible = false"
                       size="small">{{ $t('Cancel') }}</el-button>
            <!-- <el-button type="primary"
                       size="small"
                       @click="dataFormSubmitHandle()">{{ $t('Save') }}</el-button> -->
            <el-button type="primary"
                       size="small"
                       @click="submitFormMoreEidt('moreEditDataForm')">{{ $t('Save') }}</el-button>
          </template>
        </el-dialog>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import getFlowSetting from './TruggerTemplate'
import JiraNumberLink, { JiraNumberMixin } from '@/components/jira-number-link'
import qs from 'qs'
import Cookies from 'js-cookie'
import {fetchBotTemplates,checkBotName,createBot,updateBot,fetchBot,deleteTag} from '@/api/new'
import ZTooltip from '@/components/storybook/z-tooltip'
import bus from '@/components/storybook/utilties/bus'

export default {
  components: {
    JiraNumberLink,
    ZTooltip
  },
  mixins: [JiraNumberMixin],
  props: ['parentStateObj', 'botType', 'isClone','editType'],
  data () {
    return {
      visible: false,
      loading: false,
      submitBtnLoading: false,
      editEmptyBot: false,
      stateObj: -1,
      templatesList: [],
      dataForm: {
        status: !this.$hasPermission('sys:bots:moreedit') ? 'Published' : 'Requested',
        businessType: this.$route.path.includes('CrossTenant') ? 'MSPbots Internal' : 'Custom',
        id: null,
        name: null,
        integration: null,
        roleIdList: this.$store.state.defaultRoleList,
        description: null,
        newType: 0,
        tenantCode: this.$store.state.user.tenantCode,
        shared: false,
        applyTenant: false,
        teamId: null,
        classification: '',
        da: this.$store.state.user.id,
        po: '',
        jiraNumber: '',
        tagList: []
      },
      integrationList: [],
      triggerImgUrl: [
        'https://us.flow.microsoft.com/Content/retail/assets/scheduledCard.66b44d1c1967f652f7a5734b82e127ec.2.svg',
        'https://us.flow.microsoft.com/Content/retail/assets/instantCard.712e68fa8273fff7fa5ee2bf5e6b6fd7.2.svg',
        'https://us.flow.microsoft.com/Content/retail/assets/automatedCard.3145b0aff51761bc7685f5fcc4104355.2.svg',
        'https://us.flow.microsoft.com/Content/retail/assets/uiFlowCard.0e38415014af5cf1423e6e99791b526b.2.svg',
        'https://us.flow.microsoft.com/Content/retail/assets/bpfCard.405428c580d33a66cbca1de80a343334.2.svg'
      ],
      tempNumber: 0,
      moreEditVisible: false,
      userList: [],
      assignRoleList: [],
      roleList: [],
      tags: [],
      gadgetId: ''
    }
  },
  watch: {
    visible (val) {
      if (!val) {
        this.$root.eventBus.$emit('bus:tag-refresh')
      }
    }
  },
  computed: {
    businessTypeList () {
      try {
        if (this.$hasPermission('sys:widget:type:mspbots internal') && this.$route.path.includes('CrossTenant')) {
          return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList.filter(item => {
            return item.dictValue === 'MSPbots Internal'
          })
        } else {
          return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list').dataList.filter(item => {
            return item.dictValue !== 'MSPbots Internal'
          })
        }
      } catch (error) {
        return []
      }
    },
    statusList () {
      try {
        var list = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_status_list').dataList
        if (this.$hasPermission('sys:widget:publishauth')) {
          return list
        } else {
          return this._.reject(this._.reject(list, { dictValue: 'Alpha' }), { dictValue: 'Published' })
        }
      } catch (error) {
        return []
      }
    },
    dataFormRules () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { min: 0, max: 69, message: this.$t('custom.tips.valueLength', { length: '70' }), trigger: 'change' },
          { required: true, message: this.$t('custom.tips.required', { fields: 'Name' }), trigger: 'blur' },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        description: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Description' }), trigger: 'blur' },
          { min: 0, max: 499, message: this.$t('custom.tips.valueLength', { length: '500' }), trigger: 'change' }
        ],
        roleIdList: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    FormRules () {
      return {
        businessType: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Type' }), trigger: 'change' }
        ],
        tenantCode: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Client' }), trigger: 'change' }
        ],
        status: [
          { required: true, message: this.$t('custom.tips.required', { fields: 'Status' }), trigger: 'change' }
        ]
      }
    },
    canEditModel () {
      return Boolean(!this.dataForm.id || this.editEmptyBot)
    },
    isStartFromTemplate () {
      return Boolean(typeof this.stateObj === 'object' && this.stateObj['type'] !== 'trigger')
    },
    comDialogTop () {
      return window.innerHeight > 688 ? (window.innerHeight - 688) / 2 : 20
    },
    classificationList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'bots_classification_list').dataList || []
    },
    reselectBtn () {
      let temp = false
      temp = !this.$store.state.bot.dataFromEidt
      if (this.$store.state.bot.dataFromWidget && this.$store.state.bot.dataFromWidget !== undefined) {
        temp = false
      }
      return temp
    },
    fullRoleList () {
      let roleList = this.roleList
      let assignRoleList = this.assignRoleList
      let roleTemp = []
      let assignTemp = []
      let temp = []
      roleList.forEach(ii => {
        roleTemp.push({
          roleId: ii.roleId,
          name: ii.name
        })
      })
      assignRoleList.forEach(it => {
        assignTemp.push({
          roleId: it.assignId,
          name: ''
        })
      })
      temp = this._.intersectionBy(roleTemp, assignTemp, 'roleId')
      return temp
    }
  },
  methods: {
    getRoleList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.system.getClientRoleListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.roleList = res.data
        }).catch(() => { })
    },
    getAssignRoleList () {
      let temp = []
      let roleList = this.$store.state.user.roleList
      roleList.forEach(it => {
        temp.push(it.id)
      })
      var params = qs.stringify({
        'roleId': temp
      }, { arrayFormat: 'repeat' })
      this.$interface.um.getAssignRoleList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.assignRoleList = res.data
      })
    },
    submitFormMoreEidt (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.moreEditVisible = false
        } else {
          return false
        }
      })
    },
    getUserList () {
      const params = {
        datasetKey: 'qwerdsafsadrtfzgsadfggs'
      }
      this.$interface.reports.getDrillThroughDataInfo(params).then(({ data: res }) => {
        if (res.data) {
          this.userList = res.data
        }
      })
    },
    deleteTag(tag) {
      if (!tag) return false
      this.$confirm('Are you sure to delete?','warning', {
        type: 'warning',
      })
        .then(async () => {
          const params = {
            id: tag.id,
          }
          const { data: res } = await deleteTag(params)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm.tagList = this.dataForm.tagList&&this.dataForm.tagList.filter(
            item => item!== tag.name
          )
          this.getTags().then(() => {
            bus.$emit('update:tags', this.tags)
          })
          this.$message.success(res.msg)
          
        }).catch((err) => {
          console.log(err);
        })
    },
    async getTags () {
      try {
        const { tags } = this.$interface.reports
        const { get } = this._
        const params = {}

        const { data: response } = await tags(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.tags = get(response, 'data', [])
      } catch (error) {

      } finally {

      }
    },
    validatePass (rule, value, callback) {
      let params = {
        name: this.dataForm.name,
        id: this.isClone ? '' : (this.dataForm.id ? this.dataForm.id : '')
      }
      checkBotName(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return callback(new Error(res.msg))
          }
          callback()
        })
    },
    botsMoreEdit () {
      if (!this.dataForm.teamId) {
        this.dataForm.teamId = ''
      }
      this.moreEditVisible = true
    },
    validateClick () {
      if (this.canEditModel) {
        return true
      } else {
        this.$message.warning('This mode does not support modifying Start from blank. Please carefully select the Start from blank you need when adding.')
        return false
      }
    },
    init (gadgetId) {
      this.gadgetId = gadgetId
      this.visible = true
      this.getUserList()
      this.getRoleList()
      this.getAssignRoleList()
      this.getTags()
      this.$nextTick(() => {
        this.getTemplateList()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    getInfo () {
      const _this = this
      this.loading = true
      const params = {
        id: this.dataForm.id
      }
      fetchBot(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return _this.$message.error(res.msg)
          }
          _this.loading = false
          _this.dataForm = {
            ..._this.dataForm,
            ...res.data
          }
          _this.dataForm.tenantCode = _this.dataForm.tenantCode || this.$store.state.user.tenantCode
          _this.editEmptyBot = false
          // if (res.data.sysBotScriptList.length > 0) {
          //   _this.stateObj = res.data.sysBotScriptList[0]
          // } else {
          //   _this.editEmptyBot = true
          // }

          if (res.data.originalId) {
            _this.setDefaultStateObj(res.data.originalId)
          }
        }).catch(() => {
        })
    },
    setDefaultStateObj (originalId) {
      this.tempNumber++
      if (this.templatesList.length > 0) {
        this.stateObj = this.templatesList.find(e => e.id === originalId)
        this.dataForm.integration = this.stateObj.integration
        this.tempNumber = 0
      } else if (this.tempNumber < 10) {
        setTimeout(() => {
          this.setDefaultStateObj(originalId)
        }, 1000)
      }
    },
    getTemplateList () {
      fetchBotTemplates()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.templatesList = res.data
        })
    },
    botsClone () {
      const params = {
        businessType: this.dataForm.businessType,
        tenantCode: Cookies.get('tenant_code') || '',
        roleIdList: this.dataForm.roleIdList,
        newType: 3,
        originalId: this.dataForm.id,
        name: this.dataForm.name,
        description: this.dataForm.description,
        status: this.dataForm.status,
        tagList: this.dataForm.tagList
      }
      createBot(params).then(res => {
        this.submitBtnLoading = false
        if (res.data.code !== 0) {
          return this.$message.error(res.data.msg)
        }
        this.addNewRouter(res.data.data)
        this.$emit('refreshList')
        this.canceldialog()
        this.$message.success(res.data.msg)
      }).catch(err => {
        this.submitBtnLoading = false
        console.log(err)
      })
    },
    async dataFormSubmitHandle () {
      if (this.$store.state.user.username.includes('mspbots.ai') && this.$hasPermission('sys:bots:moreedit') && !this.isClone) {
        if (!this.dataForm.da) {
          return this.$message.error(this.$t('custom.component.gadget.da'))
        }
        if (!this.dataForm.po) {
          return this.$message.error(this.$t('custom.component.gadget.po'))
        }

        const isMatchJiraNumber = await this.checkJiraNumber(this.dataForm.jiraNumber)

        if (!isMatchJiraNumber) {
          return this.$message.error(this.$t('custom.component.gadget.checkNumber'))
        }
      }
      this.stateObj = this._.cloneDeep(this.parentStateObj)
      let _self = this
      if (this.dataForm.tenantCode === '1001' && this.dataForm.businessType === 'Custom' && this.$store.state.user.tenantCode !== '1001') {
        return this.$message.error('The login person is the default tenant, then the type of widget cannot be Custom.')
      }
      this.submitBtnLoading = true
      this.validateForm()
        .then(() => {
          if (Object.keys(this.stateObj).length === 0 && !this.$store.state.bot.dataFromEidt) {
            this.submitBtnLoading = false
            return this.$message.error('Please select the template of the QABot.')
          }
          if (this.isClone) {
            return this.botsClone()
          }
          let params = {}
          if (_self.botType === 'Store' || _self.botType === 'template') {
            params = {
              originalId: _self.parentStateObj.id,
              name: _self.dataForm.name,
              description: _self.dataForm.description,
              businessType: _self.dataForm.businessType,
              tenantCode: _self.dataForm.tenantCode,
              status: _self.dataForm.status,
              newType: _self.botType === 'Store' ? 3 : 2,
              da: _self.dataForm.da,
              po: _self.dataForm.po,
              tagList: _self.dataForm.tagList,
              jiraNumber: _self.dataForm.jiraNumber,
              roleIdList: _self.dataForm.roleIdList
            }
          } else if (_self.botType === 'script') {
            const flowSettingObj = getFlowSetting(_self.stateObj.triggerEvent, _self.stateObj)
            params = {
              ..._self.dataForm
            }
            if (_self.canEditModel) {
              params.triggerType = _self.stateObj.triggerEvent
              params.newType = 1
              params['flowSetting'] = flowSettingObj.flowSetting
              params['sysBotScriptList'] = [
                {
                  botId: '',
                  name: _self.stateObj.name,
                  paramsValue: flowSettingObj.paramsvaluesend,
                  scriptId: _self.stateObj.id,
                  trackId: flowSettingObj.trackid,
                  triggerId: ''
                }
              ]
            }
          }
          if (_self.$store.state.bot.dataFromEidt) {
            params = {
              ..._self.dataForm
            }
          }
          params.teamId = _self.dataForm.teamId
          params.classification = params.classification ? params.classification : _self.getClassification()
          const changeBotInfo = () => {
            if (!_self.dataForm.id) {
              delete params.id
              delete params.integration
              return createBot(params)
            } else {
              return updateBot(params)
            }
          }
          changeBotInfo().then(({ data: res }) => {
            if (_self.$store.state.bot.dataFromEidt) _self.$store.commit('REFRESHBOTLIST', 'refresh')
            _self.$emit('closeQuery')
            _self.submitBtnLoading = false
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            _self.$emit('refreshList')
            if (_self.canEditModel) {
              if (!_self.gadgetId) {
                _self.resetFieldsDataForm()
              }
              _self.$store.commit('RECORDBOTID', res.data.id)
              // this.$router.push({ name: 'mspbots-bots-bak-bot-view-index', query: { botId: res.data.id, from: 'newBot' } })
              // this.$router.push({ name: 'mspbots-bots-bak-bot-design-index', query: { botId: res.data.id, from: 'newBot' } })
              // if (_self.pathRoute && _self.pathRoute === 'DESIGN') {
              //   _self.$router.push({ name: 'mspbots-bots-bak-bot-design-index', query: { botId: res.data.id } })
              // } else {
              this.addNewRouter(res.data)

              // }
              // } else {
              //   this.resetFieldsDataForm()
              this.$nextTick(() => {
                this.$store.state.contentTabs.forEach(item => { if (item.menuId === res.data.id) item.title = res.data.name })
              })
            }
              this.$store.state.contentTabs.forEach(item => {
                 if (item.menuId === res.data.id) {
                  if(this.editType) {
                    // this.$store.state.contentTabsActiveName=res.data.name
                  }
                  item.title = res.data.name
                  item.name = res.data.name
                  item.query.name = res.data.name
                  }
                })
            _self.$store.commit('BOTFORMEDIT', false)
            _self.$store.commit('BOTFORMWIDGET', false)
            _self.canceldialog()
            _self.$message.success(res.msg)
          }).catch(() => {
            this.submitBtnLoading = false
          })
        })
        .catch(() => {
          this.submitBtnLoading = false
        })
    },
    addNewRouter (row) {
      this.$router.push({
        path: `bot-${row.id}`,
        query: {
          pageid: 'botdetail',
          botId: row.id,
          name: row.name,
          gadgetId: this.gadgetId
        }
      })
      if (this.gadgetId) {
        this.resetFieldsDataForm()
      }
    },
    resetFieldsDataForm () {
      this.visible = false
      this.dialogBeforeClosed()
    },
    canceldialog () {
      this.visible = false
      this.dialogBeforeClosed()
      // this.$emit('refreshList')
    },
    reselectTem () {
      this.$emit('reselectTemplate', true)
    },
    dialogBeforeClosed () {
      this.$refs.dataForm.resetFields()
      if (this.$refs.moreEditDataForm) {
        this.$refs.moreEditDataForm.resetFields()
      }
      this.$store.commit('BOTFORMEDIT', false)
      this.$store.commit('BOTFORMWIDGET', false)
      Object.assign(this.$data, this.$options.data.call(this))
    },
    validateForm () {
      return this.$refs.dataForm.validate()
    },
    getClassification () {
      let temp = ''
      if (this.parentStateObj.classification) {
        temp = this.parentStateObj.classification
      } else {
        if (this.botType === 'script') {
          temp = this.classificationList[0].dictValue
        }
      }
      return temp
    }
  }
}
</script>

<style lang="scss" scoped>
@import "src/views/modules/mspbots/bots-bak/my-bots/add-or-update";
.addBotFooter {
      width: 100%;
      padding: 20px;
      display: flex;
      // flex-direction: row-reverse;
      justify-content: flex-end;

    }
.card-border {
  box-shadow: 0px 0px 8px 0px #229aea !important;
}
::v-deep .el-dialog__body {
  height: 460px;
}
.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #606266;
}
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0!important;
}
</style>
<style lang="scss">
.cui-custom-css-bot-edit {
  .el-dialog__body {
    padding: 0;
  }
  .el-form-item {
    margin-bottom: 10px !important;
  }
}
</style>
